package com.piece.admin.controller;

import com.piece.admin.api.dto.SysUserDTO;
import com.piece.admin.support.UserInfoSupport;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.constant.ApplicationConstants;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.dto.ConfigDTO;
import com.piece.core.framework.support.dto.UserDetailDTO;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.collection.CollectionUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.time.DateUtil;
import com.piece.core.oauth.social.AuthRequestFactory;
import com.piece.core.web.util.ServletUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@Api(tags = {"页面跳转管理"})
public class PageController extends ControllerSupport {

    private final String user_path_prefix = "/user/";
    private final String tool_path_prefix = "/tool/";
    private final String client_path_prefix = "/client/";
    private final String log_path_prefix = "/log/";
    private final String demo_path_prefix = "/demo/";

    @Autowired
    private AuthRequestFactory authRequestFactory;

    @ResponseBody
    @GetMapping("/public/oauth/list")
    @ApiOperation(value = "获取链接登录地址")
    public AjaxResponse oauthList() {
        List<ConfigDTO> configs = new ArrayList<>();
        List<String> result = authRequestFactory.socialList();
        if (CollectionUtil.isNotEmpty(result)) {
            for (String key : result) {
                configs.add(ConfigDTO.builder().name(key).value(key).build());
            }
        }

        return success(configs);
    }

    // 首页
    @GetMapping("/api/index")
    @ApiOperation(value = "加载首页页面", notes = "加载菜单属性{menus}，加载用户信息{user}")
    public String index(ModelMap modelMap, UserDetailDTO userDetail) {
        SysUserDTO user = (SysUserDTO) userDetail.getDetail();
//      List<TbSysMenu> menus = tbSysMenuService.findByUser(user);
//      menus = tbSysMenuService.findChildMenus(menus, 0L);
//      modelMap.put("menus", menus);
        modelMap.put("user", user);
        modelMap.put("origin", getRequestPrefix());
        modelMap.put("singlePage", Convert.toBool(applicationProperties.getValue(ApplicationConstants.APPLICATION_SINGLE_PAGE), true));
        modelMap.put("demoEnabled", Convert.toBool(applicationProperties.getValue(ApplicationConstants.APPLICATION_DEMO_ENABLE), false));
        if (UserInfoSupport.isAdminRole(user.getUserId())) {
            modelMap.put("manageEnabled", true);
        } else {
            modelMap.put("manageEnabled", false);
        }
        return "/index";
    }

    @GetMapping("/api/home")
    public String goHome() {
        return "/home";
    }

    @GetMapping("/api/user/{path}")
    public String goUser(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setLayerInfo();
        return user_path_prefix + path;
    }

    @GetMapping("/api/tool/dict/{path}")
    @AclPermission(code = "system:dict:view")
    public String goDict(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setParameter("dictGroup", getRequest().getParameter("dictGroup"));
        setParameter("dictCodes", getRequest().getParameter("dictCode"));
        return tool_path_prefix + "dict/" + path;
    }

    @GetMapping("/api/tool/config/{path}")
    @AclPermission(code = "tool:config:view")
    public String goConfig(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        return tool_path_prefix + "config/" + path;
    }

    @GetMapping("/api/tool/black/{path}")
    @AclPermission(code = "monitor:black:view")
    public String goBlack(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        return tool_path_prefix + "black/" + path;
    }

    @GetMapping("/api/tool/gen/{path}")
    @AclPermission(code = "tool:gen:view")
    public String goGen(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setLayerInfo();

        String table = getRequest().getParameter("table");
        if (StringUtil.isNotEmpty(table)) {
            getRequest().setAttribute("tableName", table);
        }
        String column = getRequest().getParameter("column");
        if (StringUtil.isNotEmpty(column)) {
            getRequest().setAttribute("columnName", column);
        }
        return tool_path_prefix + "gen/" + path;
    }

    @GetMapping("/api/client/oauth/{path}")
    @AclPermission(code = "client:oauth:view")
    public String goOauthClient(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setLayerInfo();
        return client_path_prefix + "oauth/" + path;
    }

    @GetMapping("/api/client/file/{path}")
    @AclPermission(code = "client:file:view")
    public String goFileClient(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setLayerInfo();
        return client_path_prefix + "file/" + path;
    }

    @GetMapping("/api/client/sms/{path}")
    @AclPermission(code = "client:sms:view")
    public String goSmsClient(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setLayerInfo();
        return client_path_prefix + "sms/" + path;
    }

    @GetMapping("/api/log/{path}")
    @AclPermission(code = "monitor:log:view")
    public String goLog(@PathVariable String path) {
        setBreadCrumb();
        setBaseModel();
        setLayerInfo();
        return log_path_prefix + path;
    }

    @GetMapping("/api/log/poll")
    @AclPermission(code = "monitor:log:quartz:view")
    @ApiOperation("查看实时日志信息")
    public String pollLog() {
        setLayerInfo();
        getRequest().setAttribute("path", getRequestPrefix());
        return log_path_prefix + "pollLog";
    }

    @GetMapping("/monitor/druid")
    @AclPermission(code = "monitor:druid:view")
    @ApiOperation(value = "跳转Druid监控控制台")
    public String druid() {
        setAuthInfo();
        return redirect("/druid/index");
    }

    @GetMapping("/api/tool/swagger")
    @AclPermission(code = "tool:swagger:view")
    public String swagger() {
        setAuthInfo();
        return redirect("/doc.html");
    }

    @GetMapping("/api/spider/flow/editor/html")
    @AclPermission(code = "tool:swagger:view")
    public String spiderEditor() {
        setAuthInfo();
        String id = getRequest().getParameter("id");
        String accessToken = getRequest().getParameter("access_token");
        String ctx = ServletUtil.getRequestPrefix(contextPath);
        String param = "";
        param += "?date=" + DateUtil.getDateNow("yyyyMMddHHmmss");
        if (StringUtil.isNotEmpty(accessToken)) {
            param += "&access_token=" + accessToken;
        }
        if (StringUtil.isNotEmpty(ctx)) {
            param += "&ctx=" + ctx;
        }
        if (StringUtil.isNotEmpty(id)) {
            param += "&id=" + id;
        }

        return redirect("/editor.html" + param);
    }

    @GetMapping("/api/demo/form/{path}")
    public String goForm(@PathVariable String path) {
        return demo_path_prefix + "form/" + path;
    }

    @GetMapping("/api/demo/icon/{path}")
    public String goIcon(@PathVariable String path) {
        return demo_path_prefix + "icon/" + path;
    }

    @GetMapping("/api/demo/modal/{path}")
    public String goModal(@PathVariable String path) {
        setBaseModel();
        return demo_path_prefix + "modal/" + path;
    }

    @GetMapping("/api/demo/modal/table/{path}")
    public String goModalTable(@PathVariable String path) {
        setBaseModel();
        return demo_path_prefix + "modal/table/" + path;
    }

    @GetMapping("/api/demo/report/{path}")
    public String goReport(@PathVariable String path) {
        return demo_path_prefix + "report/" + path;
    }

    @GetMapping("/api/demo/table/{path}")
    public String goTable(@PathVariable String path) {
        return demo_path_prefix + "table/" + path;
    }
}
